import { ref, computed } from 'vue'
import type { IDragState, IComponent } from '@/types/designer'

// 拖拽管理器状态
const dragState = ref<IDragState>({
  isDragging: false,
  dragType: null,
  dragComponent: null,
  dragSource: null,
  dropTarget: null,
  dragPosition: { x: 0, y: 0 },
  dragOffset: { x: 0, y: 0 },
  dragStartTime: 0,
  dragStartPosition: { x: 0, y: 0 }
})

// 拖拽状态计算属性
const isDragging = computed(() => dragState.value.isDragging)
const dragType = computed(() => dragState.value.dragType)
const dragComponent = computed(() => dragState.value.dragComponent)
const dropTarget = computed(() => dragState.value.dropTarget)
const dragPosition = computed(() => dragState.value.dragPosition)

// 拖拽管理器方法
export const useDragDropManager = () => {
  // 开始拖拽
  const startDrag = (
    component: IComponent,
    type: 'new' | 'move',
    source: 'library' | 'canvas',
    event: DragEvent
  ) => {
    const startTime = Date.now()
    const startPos = { x: event.clientX, y: event.clientY }
    
    dragState.value = {
      isDragging: true,
      dragType: type,
      dragComponent: component,
      dragSource: source,
      dropTarget: null,
      dragPosition: { x: event.clientX, y: event.clientY },
      dragOffset: { x: 0, y: 0 },
      dragStartTime: startTime,
      dragStartPosition: startPos
    }
    
    // 设置拖拽数据
    if (event.dataTransfer) {
      event.dataTransfer.effectAllowed = 'copy'
      event.dataTransfer.setData('application/json', JSON.stringify({
        type,
        component,
        source
      }))
    }
    
    console.log('🚀 拖拽开始:', { type, source, component: component.type })
  }
  
  // 更新拖拽位置
  const updateDragPosition = (event: DragEvent) => {
    if (!dragState.value.isDragging) return
    
    const currentPos = { x: event.clientX, y: event.clientY }
    
    dragState.value.dragPosition = currentPos
    dragState.value.dragOffset = {
      x: currentPos.x - dragState.value.dragStartPosition.x,
      y: currentPos.y - dragState.value.dragStartPosition.y
    }
  }
  
  // 设置拖拽目标
  const setDropTarget = (target: IComponent | null) => {
    dragState.value.dropTarget = target
  }
  
  // 结束拖拽
  const endDrag = () => {
    const dragDuration = Date.now() - dragState.value.dragStartTime
    
    // 如果拖拽时间太短，可能是误操作
    if (dragDuration < 100) {
      console.log('⚠️ 拖拽时间过短，可能是误操作')
    }
    
    console.log('🏁 拖拽结束:', {
      duration: dragDuration,
      type: dragState.value.dragType,
      target: dragState.value.dropTarget?.type
    })
    
    resetDragState()
  }
  
  // 重置拖拽状态
  const resetDragState = () => {
    dragState.value = {
      isDragging: false,
      dragType: null,
      dragComponent: null,
      dragSource: null,
      dropTarget: null,
      dragPosition: { x: 0, y: 0 },
      dragOffset: { x: 0, y: 0 },
      dragStartTime: 0,
      dragStartPosition: { x: 0, y: 0 }
    }
  }
  
  // 查找拖拽目标
  const findDropTarget = (event: DragEvent): IComponent | null => {
    const elements = document.elementsFromPoint(event.clientX, event.clientY)
    
    for (const element of elements) {
      const componentId = element.getAttribute('data-component-id')
      if (componentId) {
        // 这里需要从store中查找组件，暂时返回null
        // TODO: 实现组件查找逻辑
        return null
      }
    }
    
    return null
  }
  
  // 判断组件是否可以接受拖拽
  const canAcceptDrop = (targetComponent: IComponent, dragComponent: IComponent): boolean => {
    // 不能拖拽到自己
    if (targetComponent.id === dragComponent.id) {
      return false
    }
    
    // 容器组件可以接受任何组件
    if (targetComponent.type === 'container') {
      return true
    }
    
    // 其他组件不能接受拖拽
    return false
  }
  
  // 处理拖拽放置
  const handleDrop = (event: DragEvent, targetComponent?: IComponent) => {
    event.preventDefault()
    
    try {
      const data = JSON.parse(event.dataTransfer?.getData('application/json') || '{}')
      const { type, component, source } = data
      
      if (!type || !component) {
        console.error('❌ 拖拽数据无效:', data)
        return
      }
      
      console.log('🎯 拖拽放置:', { type, source, target: targetComponent?.type })
      
      // 这里可以触发拖拽完成事件
      // TODO: 实现拖拽完成逻辑
      
    } catch (error) {
      console.error('拖拽数据解析失败:', error)
    } finally {
      endDrag()
    }
  }
  
  // 处理拖拽悬停
  const handleDragOver = (event: DragEvent) => {
    event.preventDefault()
    event.dataTransfer!.dropEffect = 'copy'
    
    updateDragPosition(event)
    
    // 查找并设置拖拽目标
    const target = findDropTarget(event)
    setDropTarget(target)
  }
  
  // 处理拖拽离开
  const handleDragLeave = (event: DragEvent) => {
    // 可以在这里实现拖拽离开逻辑
    // 比如清除高亮效果等
  }
  
  return {
    // 状态
    dragState,
    isDragging,
    dragType,
    dragComponent,
    dropTarget,
    dragPosition,
    
    // 方法
    startDrag,
    updateDragPosition,
    setDropTarget,
    endDrag,
    resetDragState,
    findDropTarget,
    canAcceptDrop,
    handleDrop,
    handleDragOver,
    handleDragLeave
  }
}
